package com.baitengsoft.patentapimonitor.api.service.impl;

import com.baitengsoft.patentapimonitor.api.dao.PacApplicantDao;
import com.baitengsoft.patentapimonitor.api.dao.WebApplicantindustryRlatDao;
import com.baitengsoft.patentapimonitor.api.dao.WebApplicanttypeRlatDao;
import com.baitengsoft.patentapimonitor.api.dao.WebPlatFormAreaDao;
import com.baitengsoft.patentapimonitor.api.entity.PacApplicantEntity;
import com.baitengsoft.patentapimonitor.api.entity.WebApplicantindustryRlatEntity;
import com.baitengsoft.patentapimonitor.api.entity.WebPlatformareaEntity;
import com.baitengsoft.patentapimonitor.api.model.PacApplicantInfo;
import com.baitengsoft.patentapimonitor.api.model.PacApplicantModel;
import com.baitengsoft.patentapimonitor.api.model.WebApplicantIndustryInfo;
import com.baitengsoft.patentapimonitor.api.model.WebIndustryInfo;
import com.baitengsoft.patentapimonitor.api.model.param.ClassifyByAreaParam;
import com.baitengsoft.patentapimonitor.api.model.param.ClassifyByIndustryParam;
import com.baitengsoft.patentapimonitor.api.model.param.ClassifyByTypeParam;
import com.baitengsoft.patentapimonitor.api.model.param.SearchApplicantParam;
import com.baitengsoft.patentapimonitor.api.service.CfgDictionaryService;
import com.baitengsoft.patentapimonitor.api.service.PacApplicantService;
import com.baitengsoft.patentapimonitor.api.service.PacIndustryService;
import com.baitengsoft.patentapimonitor.common.utils.PageResult;
import com.baitengsoft.patentapimonitor.common.utils.Res;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import springfox.documentation.annotations.ApiIgnore;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by QEK on 2017/12/21.
 */
@Service
public class PacApplicantServiceImpl extends BaseServiceImpl<PacApplicantEntity> implements PacApplicantService {

    @Autowired
    private PacApplicantDao pacApplicantDao;
    @Autowired
    private CfgDictionaryService cfgDictionaryService;
    @Autowired
    private WebPlatFormAreaDao webPlatFormAreaDao;
    @Autowired
    private PacIndustryService pacIndustryService;
    @Autowired
    private WebApplicantindustryRlatDao webApplicantindustryRlatDao;

    /**
     * 分页、条件查询 权利人列表
     * @param searchApplicantParam
     * @return
     */
    @Override
    public PageResult<PacApplicantModel> pageQueryPacApplicant(SearchApplicantParam searchApplicantParam) {
        int pageNumber = searchApplicantParam.getPageNumber();
        int pageSize = searchApplicantParam.getPageSize();
        Page<Object> page = PageHelper.startPage(pageNumber, pageSize);
        List<PacApplicantModel> models = pacApplicantDao.selectPacApplicant(searchApplicantParam);
        Long count = page.getTotal();
        return new PageResult<PacApplicantModel>(models,pageNumber,pageSize,count.intValue());
    }

    @Override
    public Res classifyByIndustry(ClassifyByIndustryParam param) {
        return null;
    }

    /**
     * 获取二级类型名称拼接
     * @param arr
     * @return
     */
    private String getTypeLevel2Name(String[] arr) {
        List<Integer> idList = new ArrayList<>();
        for(int i = 0 ;i < arr.length ;i++ ){
            if(!arr[i].isEmpty()){
                idList.add(Integer.valueOf(arr[i]));
            }
        }
        List<String> strList = pacApplicantDao.selectTypeLevel2NameByIds(idList);
        String typeLevel2Name = "";
        if(strList != null && strList.size() > 0){
            typeLevel2Name = strList.toString();
            return typeLevel2Name.substring(1,typeLevel2Name.length()-1);
        }
        return "";
    }



    /**
     * 区域归类
     * @param param
     * @return
     */
    @Override
    public Res classifyByArea(ClassifyByAreaParam param) {
        int result = pacApplicantDao.classifyByArea(param);
        if(result > 0){
            return Res.ok("归类成功！");
        }
        return Res.error("归类失败！");
    }

    /**
     * 类型归类
     * @param param
     * @return
     */
    @Override
    public Res classifyByType(ClassifyByTypeParam param) {
        int result = pacApplicantDao.classifyByType(param);
        if(result > 0){
            return Res.ok("归类成功！");
        }
        return Res.error("归类失败！");
    }


    /**
     * 根据id查询详情
     * @param id
     * @return
     */
    @Override
    public PacApplicantModel selectPacApplicantById(Integer id) {
        return pacApplicantDao.selectPacApplicantById(id);
    }

    /**
     * 修改
     * @param model
     * @return
     */
    @Override
    public Res updateApplicantById(PacApplicantModel model,Integer id) {
        if(model.getAppId() != null){
            PacApplicantEntity entity = queryById(model.getAppId());
            entity.setName(model.getAppName());
            entity.setAddress(model.getAddress());
            entity.setUpdatedate(new Date());
            entity.setIndustryid(model.getIndustryId());
            entity.setAreaid(model.getAreaId());
            entity.setTypelevel1(model.getTypeLevel1());
            entity.setUpdateoperid(id);
            int result = updateByNotNull(entity);
            if(result == 1){
                return Res.ok("修改成功！");
            }
            return Res.error("修改失败！");
        }
        return Res.error("参数错误！");
    }

    @Override
    public int selectCountWithOutArea(Integer platformid) {
        Example example = new Example(PacApplicantEntity.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("platformid",platformid);
        criteria.andEqualTo("areaid",0);
        return pacApplicantDao.selectCountByExample(example);
    }

    /**
     * 分页查询
     */
    @Override
    public PageResult<PacApplicantInfo> queryList(Integer platformid, SearchApplicantParam param) {
        Page<Object> page = PageHelper.startPage(param.getPageNumber(), param.getPageSize());
        List<PacApplicantInfo> infos = pacApplicantDao.queryList(platformid,param);
        Map<String, String> applyPersonType = cfgDictionaryService.getApplyPersonType();
        for (PacApplicantInfo info :infos){
            if (StringUtils.isBlank(info.getIndustryName())) {
                info.setIndustryName("未分类");
            }
            info.setApplicantType(applyPersonType.get(info.getType().toString()));
            if (info.getAreaId()!=null){
                WebPlatformareaEntity entity = webPlatFormAreaDao.selectByPrimaryKey(info.getAreaId());
                if (entity!=null&&StringUtils.isNotBlank(entity.getName())){
                    info.setAreaName(entity.getName());
                }else {
                    info.setAreaName("");
                }
            }else {
                info.setAreaName("");
            }
        }
        Long total = page.getTotal();
        return new PageResult<>(infos,param.getPageNumber(),param.getPageSize(),total.intValue());
    }

    /**
     * 获取权力人信息
     */
    @Override
    public PacApplicantInfo getApplicantInfo(Integer applicantId) {
        PacApplicantEntity entity = pacApplicantDao.selectByPrimaryKey(applicantId);
        PacApplicantInfo info = new PacApplicantInfo();
        info.setApplicantId(entity.getId());//权力人Id
        info.setAddress(entity.getAddress());//权力人地址
        info.setApplicantName(entity.getName());//权力人名称
        if (entity.getAreaid()==null|| entity.getAreaid()==0){
            info.setAreaName("未分类");
            info.setAreaId(0);
        }else {
            WebPlatformareaEntity area = webPlatFormAreaDao.selectByPrimaryKey(entity.getAreaid());
            info.setAreaName(area.getName());
            info.setAreaId(entity.getAreaid());
        }
        //根据权力人ID查询行业
        List<Integer> industryIds  = pacIndustryService.getIndustryIdByApplicentId(applicantId);
        info.setIndustryIds(industryIds);
        return info;
    }

    @Override
    public Integer getPlatformIdByApplicantId(Integer applicantId) {
        PacApplicantEntity entity = pacApplicantDao.selectByPrimaryKey(applicantId);
        if (entity == null) return null;
        return entity.getPlatformid();
    }

    /**
     * 查询该平台下所有权力人ID
     */
    @Override
    public List<Integer> getApplicantIdsByPlatfromId(Integer platformid) {
        if (platformid == null|| platformid <0) return new ArrayList<>();
        return pacApplicantDao.getApplicantIdsByPlatfromId(platformid);
    }

    /**
     * 权利人区域归类
     */
    @Override
    public void classifyAreaByIds(List<Integer> ids, Integer areaId) {
        pacApplicantDao.classifyAreaByIds(ids,areaId);
    }

    /**
     * 根据Id行业归类
     */
    @Override
    public void classifyIndustry(List<Integer> applicantIdList, List<Integer> industryIdList) {
        //删除所有绑定
        Example example = new Example(WebApplicantindustryRlatEntity.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andIn("applicantid",applicantIdList);
        webApplicantindustryRlatDao.deleteByExample(example);
        List<WebApplicantindustryRlatEntity> entityList =new ArrayList<>();
        for (Integer id :applicantIdList){
            for (Integer inId: industryIdList){
                WebApplicantindustryRlatEntity entity = new WebApplicantindustryRlatEntity();
                entity.setApplicantid(id);
                entity.setIndustryid(inId);
                entityList.add(entity);
            }
        }
        webApplicantindustryRlatDao.insertList(entityList);
    }

    @Override
    public Res updatePacApplicant(Integer platformId,PacApplicantInfo info) {
        PacApplicantEntity entity = pacApplicantDao.selectByPrimaryKey(info.getApplicantId());
        if (entity == null) return Res.error("未查询到该权利人");
        List<Integer> areaIds = webPlatFormAreaDao.selectAreaIdByPlatFormId(platformId);
        if(!areaIds.contains(info.getAreaId())) return Res.error("参数有误");
        List<Integer> industryIds = pacIndustryService.getIndustryIdsByPlatformId(platformId);
        if (!industryIds.containsAll(info.getIndustryIds())) return Res.error("参数有误");
        entity.setAreaid(info.getAreaId());
        List<Integer> applicantIdList = new ArrayList<>();
        applicantIdList.add(info.getApplicantId());
        classifyIndustry(applicantIdList,info.getIndustryIds());
        int i = pacApplicantDao.updateByPrimaryKey(entity);
        return Res.ok("修改成功");
    }


}
